﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http.SelfHost;
using System.Web.Http;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
using System.Web.Http.Filters;

namespace AutoUpdateTool.Utils
{
    /// <summary>
    /// 自宿主WebApi服务
    /// </summary>
    public class SelfHostUtils
    {
        private static HttpSelfHostServer _server = null;
        private static bool _running = false;
        public static HttpSelfHostServer Server
        {
            get { return _server; }
        }
        public static bool IsRunning
        {
            get { return _running; }
        }
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="host"></param>
        /// <param name="rootPath"></param>
        /// <returns></returns>
        public static bool StartServer(string host)
        {
            if (!IsHttpAddress(host) && !IsIPAddress(host)) return false;
            if (_server != null) return true;

            var baseHost = host;
            if (IsIPAddress(baseHost) && !IsHttpAddress(baseHost))
            {
                baseHost = "http://" + host;
            }
            var uri = new Uri(baseHost.TrimEnd('/'));
            baseHost = uri.AbsoluteUri.Replace(uri.AbsolutePath, "") + "/";

            //Assembly.Load("AutoUpdateTool"); //手工加载apicontroller程序集

            // 创建HttpListener对象
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add(baseHost);
            listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;

            var config = new HttpSelfHostConfiguration(baseHost);
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            //config.MaxConcurrentRequests = 10000;
            config.MaxReceivedMessageSize = 2147483647;
            //config.SendTimeout = TimeSpan.FromMinutes(10);
            //config.ReceiveTimeout = TimeSpan.FromMinutes(10);

            config.Routes.MapHttpRoute(
                name: "FileApi",
                routeTemplate: "api/file/{*dir}",
                defaults: new { controller = "File", action = "Get" }
            );
            _server = new HttpSelfHostServer(config);
            _server.OpenAsync();
            Console.WriteLine("Web API self-hosted on " + baseHost);
            _running = true;
            return true;
        }

        /// <summary>
        /// 关闭服务
        /// </summary>
        public static bool StopServer()
        {
            if (_server != null)
            {
                _server.CloseAsync().Wait();
                _running = false;
                _server = null;
            }
            return true;
        }

        /// <summary>
        /// 判断是否http地址
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private static bool IsHttpAddress(string input)
        {
            if (string.IsNullOrEmpty(input)) return false;
            return System.Text.RegularExpressions.Regex.IsMatch(input, @"^(http(s)?://)?(localhost|[\d.]+|\w+(\.\w+)*)(:\d+)?(/[\w-./?%&=]*)?$");
        }
        /// <summary>
        /// 判断是否IP地址
        /// </summary>
        /// <param name="input">待判断的IP地址</param>
        /// <returns></returns>
        private static bool IsIPAddress(string input)
        {
            if (string.IsNullOrEmpty(input)) return false;
            return System.Text.RegularExpressions.Regex.IsMatch(input, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}
